'use strict';

const Controller = require('egg').Controller;
const numUtil = require('../util/numUtil');

class DefineTableController extends Controller {

  async index() {
    const { ctx } = this;
    const { page = 1, pageSize = 10 } = ctx.params;
    // const query
    ctx.body = await ctx.model.DefineTable.findAll({
      limit: pageSize,
      offset: page > 0 ? (page - 1) * pageSize : 0,
    });
  }

  async show() {
    const ctx = this.ctx;
    ctx.body = await ctx.model.DefineTable.findByPk(numUtil.toInt(ctx.params.id));
  }

  async create() {
    const ctx = this.ctx;
    const { name, key } = ctx.request.body;
    const model = await ctx.model.DefineTable.create({ name, key });
    ctx.status = 201;
    ctx.body = model;
  }

  async update() {
    const ctx = this.ctx;
    const id = numUtil.toInt(ctx.params.id);
    const model = await ctx.model.DefineTable.findByPk(id);
    if (!model) {
      ctx.status = 404;
      return;
    }

    const { name, key } = ctx.request.body;
    await model.update({ name, key });
    ctx.body = key;
  }

  async destroy() {
    const ctx = this.ctx;
    const id = numUtil.toInt(ctx.params.id);
    const model = await ctx.model.DefineTable.findByPk(id);
    if (!model) {
      ctx.status = 404;
      return;
    }

    await model.destroy();
    ctx.status = 200;
  }
}

module.exports = DefineTableController;
